package com.mvp.mvpdemo.base

import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import android.widget.RelativeLayout
import androidx.appcompat.app.AlertDialog
import com.blankj.utilcode.util.ToastUtils
import com.cxz.wanandroid.ext.dp
import com.mvp.base.BaseFragment
import com.mvp.mvpdemo.R


/**
 * Created By Mahongyin
 * Date    2020/10/15 16:25
 *
 */
abstract class BaseMvpFragment<V : IBaseView, P : IPresenter<V>> : BaseFragment(), IBaseView {
    /**
     * 持有表示层
     */
    protected var mPresenter: P? = null
    protected abstract fun createPresenter(): P

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        mPresenter = createPresenter()
        mPresenter?.attachView(this as V)
        //注册生命周期监听
//        mPresenter?.let { lifecycle.addObserver(it) }
        return super.onCreateView(inflater, container, savedInstanceState)
    }


    private var alertDialog: Dialog? = null
    override fun showLoading() {
        if (alertDialog == null) {
            alertDialog = Dialog(requireContext());
            val layout = View.inflate(requireContext(), R.layout.progress, null)
            alertDialog?.apply {
                setContentView(layout)
                //点击Dialog外部消失
                setCanceledOnTouchOutside(false)
                //禁用返回键
                setCancelable(false)
            }

        }
        if (alertDialog?.isShowing() ?: true) {
            return
        } else {
            alertDialog?.show()
        }
    }
    override fun onDestroyView() {
        alertDialog?.dismiss()
        alertDialog=null
        super.onDestroyView()
    }
    override fun hideLoading() {
        if (alertDialog?.isShowing ?: false) {
            alertDialog?.dismiss()
        }

    }

    override fun showShortToast(msg: CharSequence) {
        ToastUtils.showShort(msg)
    }

    override fun showLongToast(msg: CharSequence) {
        ToastUtils.showLong(msg)
    }
}